<template>
    <div v-loading="loading">

        <el-row :gutter="20">
            <!--部门数据-->
            <el-col :span="4" :xs="24">
                <div class="head-container">
                    <el-input
                        v-model="deptName"
                        clearable
                        placeholder="请输入部门名称"
                        prefix-icon="el-icon-search"
                        size="small"
                        style="margin-bottom: 20px"
                    />
                </div>
                <div class="head-container">
                    <el-tree
                        ref="tree"
                        :data="deptOptions"
                        :expand-on-click-node="false"
                        :filter-node-method="filterNode"
                        :props="defaultProps"
                        default-expand-all
                        @node-click="handleNodeClick"
                    />
                </div>
            </el-col>
            <!--用户数据-->
            <el-col :span="20" :xs="24">
                <el-row>
                    <el-form
                        ref="searchForm"
                        :inline="true"
                        :model="searchForm"
                        class="demo-form-inline"
                    >
                        <el-form-item label="用户名" prop="username">
                            <el-input
                                v-model.trim="searchForm.username"
                                placeholder="用户名"
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="是否可用" prop="available">
                            <el-select v-model="searchForm.available" placeholder="是否可用">
                                <el-option label="全部" value=""></el-option>
                                <el-option :value="1" label="可用"></el-option>
                                <el-option :value="0" label="不可用"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="onSearch">查 询</el-button>
                            <el-button @click="resetSearchForm('searchForm')">重 置</el-button>
                        </el-form-item>
                    </el-form>
                </el-row>
                <el-row>
                    <el-button v-auth="['/user/saveOrUpdate']" type="primary" @click="addHandleClick">添加</el-button>
                    <el-button v-auth="['/user/delete']" type="danger" @click="batchDelete(tableChecked)">批量删除
                    </el-button>
                    <p/>
                </el-row>
                <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="ID" prop="id" width="35"></el-table-column>
                    <el-table-column label="用户名" prop="username" width="110">
                    </el-table-column>
                    <el-table-column align="center" label="头像" prop="avatar" width="130">
                        <template slot-scope="scope">
                            <el-image v-if="scope.row.avatar"
                                      :src="scope.row.avatar"
                                      fit="fill"
                                      style="width: 100px; height: 100px"></el-image>
                            <span v-else>无</span>
                        </template>
                    </el-table-column>
                    <el-table-column :formatter="sexFormatter" label="性别" prop="sexType" width="60">
                    </el-table-column>
                    <el-table-column :show-overflow-tooltip="true" align="center" label="部门" prop="dept.deptName"/>
                    <el-table-column label="邮箱" prop="email" width="180"></el-table-column>
                    <el-table-column label="电话" prop="tel" width="150"></el-table-column>
                    <el-table-column label="角色" align="center" prop="roles" width="150">
                        <template slot-scope="scope">
                <span
                    v-for='role in scope.row.roles' :key="role.id"
                >
                    <el-tag>{{ role.name }}</el-tag>
                </span>
                        </template>
                    </el-table-column>

                    <el-table-column
                        label="是否可用"
                        align="center"
                        prop="available"
                        width="110"
                    >
                        <template slot-scope="scope">
                            <el-tag v-if="scope.row.available == 1" type="success">可用</el-tag>
                            <el-tag v-else type="info">不可用</el-tag>
                        </template>
                    </el-table-column>

                    <!--            <el-table-column-->
                    <!--                prop="updateTime"-->
                    <!--                label="更新日期"-->
                    <!--                width="180"-->
                    <!--                :formatter="carTimeFilter"-->
                    <!--            >-->
                    <!--            </el-table-column>-->
                    <!--            <el-table-column-->
                    <!--                prop="createTime"-->
                    <!--                label="创建日期"-->
                    <!--                width="180"-->
                    <!--                :formatter="carTimeFilter"-->
                    <!--            >-->
                    <!--            </el-table-column>-->
                    <el-table-column align="center" fixed="right" label="操作" width="210px">
                        <template slot-scope="scope">
                            <el-button
                                size="small"
                                type="text"
                                @click="modifyPasswordHandleClick(scope.row)"
                            >修改密码
                            </el-button>
                            <el-button
                                size="small"
                                type="text"
                                @click="roleHandleClick(scope.row)"
                            >设置权限
                            </el-button>
                            <el-button
                                v-auth="['/user/saveOrUpdate']"
                                size="small"
                                type="text"
                                @click="editorHandleClick(scope.row)"
                            >编辑
                            </el-button
                            >
                            <el-button
                                v-auth="['/user/delete']"
                                size="small"
                                type="text"
                                @click="deleteHandleClick(scope.row)"
                            >删除
                            </el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 列表分页操作区域 -->
                <pagination :current-page="currentPage" :page-size="pageSize" :total="totalCount"
                            @handleCurrentChange="handleCurrentChange"
                            @handleSizeChange="handleSizeChange">
                </pagination>
            </el-col>
        </el-row>
        <el-dialog
            :visible.sync="authVisible"
            title="设置权限"
            width="30%">
          <span>
              <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
                           @change="handleCheckAllChange">全选</el-checkbox>
              <div style="margin: 15px 0;"></div>
              <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRolesChange">
                <el-checkbox v-for="role in roles" :key="role.id" :label="role.id">{{ role.name }}</el-checkbox>
              </el-checkbox-group>
          </span>
            <span slot="footer" class="dialog-footer">
            <el-button @click="authVisible = false">取 消</el-button>
            <el-button type="primary" @click="changeRolesClick">确 定</el-button>
          </span>
        </el-dialog>

        <el-dialog
            :visible.sync="modifyPasswordVisible"
            title="修改密码"
            width="30%">
          <span>
              <el-input v-model.trim="password" autocomplete="off"
                        placeholder="请输入新的密码" type="password"></el-input>
          </span>
            <span slot="footer" class="dialog-footer">
            <el-button @click="modifyPasswordVisible = false">取 消</el-button>
            <el-button type="primary" @click="modifyPasswordClick">确 定</el-button>
          </span>
        </el-dialog>


        <el-dialog :title="isEditor ? '编辑' : '添加'" :visible.sync="dialogAddFormVisible" @close="resetForm('form')"
                   width="600px">
            <el-form ref="form" :model="form" :rules="rules">
                <el-input v-model="form.id" autocomplete="off" type="hidden"></el-input>
                <el-form-item
                    :label-width="formLabelWidth"
                    label="用户头像"
                    prop="avatar">
                    <el-row>
                        <el-col :span="6">
                            <Upload :value="form.avatar" @input="handleUpload"></Upload>
                        </el-col>

                    </el-row>

                </el-form-item>
                <el-form-item
                    :label-width="formLabelWidth"
                    label="用户名称"
                    prop="username"
                >
                    <el-input v-model="form.username" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item :label-width="formLabelWidth" label="归属部门" prop="deptId">
                    <treeselect v-model="form.deptId" :disable-branch-nodes="true" :options="deptOptions"
                                :show-count="true"
                                placeholder="请选择归属部门"/>
                </el-form-item>

                <el-form-item
                    :label-width="formLabelWidth"
                    label="是否可用"
                    prop="available"
                >

                    <el-radio v-model="form.available" :label="1">可用</el-radio>
                    <el-radio v-model="form.available" :label="0">不可用</el-radio>
                </el-form-item>

                <el-form-item
                    :label-width="formLabelWidth"
                    label="性别"
                    prop="sexType"
                >
                    <el-switch
                        v-model="form.sexType"
                        :active-value=1
                        :inactive-value=0
                        active-text="女"
                        inactive-text="男"
                    >
                    </el-switch>
                </el-form-item>

                <el-form-item
                    :label-width="formLabelWidth"
                    label="邮箱"
                    prop="email"
                >
                    <el-input v-model="form.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item
                    :label-width="formLabelWidth"
                    label="电话"
                    prop="tel"
                >
                    <el-input v-model="form.tel" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button v-if="!isEditor" @click="resetForm('form')">重 置</el-button>
                <el-button v-if="isEditor" @click="dialogAddFormVisible = false"
                >取 消
                </el-button>
                <el-button type=" primary" @click="saveOrUpdate">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    MODIFY_PASSWORD,
    LIST_USER_URL,
    FIND_USER_URL,
    ADD_OR_EDITOR_USER_URL,
    DELETE_USER_URL,
    LOAD_ROLES_URL,
    UPDATE_USER_AND_ROLE,
    UPLOAD_URL
} from "../../utils/api.js";
import moment from "moment";
import Pagination from "@/components/Pagination/Pagination";
import Treeselect from "@riophae/vue-treeselect";
import Upload from "@/components/Upload/Upload";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getToken} from "@/utils/auth";

export default {
    components: {Pagination, Treeselect, Upload},
    data() {
        return {
            authorToken: {
                'Authorization': 'Bearer ' + getToken()
            },
            UPLOAD_URL: UPLOAD_URL,
            roleOptions: [],
            checkAll: false,
            checkedRoles: [],
            roles: [],
            isIndeterminate: true,
            loading: true,
            // 部门树选项
            deptOptions: undefined,
            // 默认显示第几页
            currentPage: 1,
            // 总条数，根据接口获取数据长度(注意：这里不能为空)
            totalCount: 1,
            pageSize: 10,
            tableData: [],
            tableChecked: [],//被选中的记录
            ids: [],//批量删除的id
            defaultProps: {
                children: "children",
                label: "label"
            },
            authUserId: '', // 定义需要设置角色的用户id
            searchForm: {
                deptId: '',
                username: "",
                available: "", //默认搜索全部
            },
            isEditor: false,
            // 部门名称
            deptName: undefined,
            dialogAddFormVisible: false,
            authVisible: false,
            modifyPasswordVisible: false,
            password: '',
            form: {
                id: "",
                username: "",
                available: 1, //默认可用
                sexType: 0,
                avatar: "",
                email: "",
                tel: "",
                deptId: undefined,
            },
            formLabelWidth: '120px',
            rules: {
                username: [{
                    required: true,
                    message: '请输入用户名称',
                    trigger: 'blur'
                },
                    {
                        min: 2,
                        max: 20,
                        message: '长度在 2 到 20个字符',
                        trigger: 'blur'
                    }
                ],
                available: [{
                    required: true,
                    message: '请选择是否可用',
                    trigger: 'blur'
                }],
                sexType: [{
                    required: true,
                    message: '请选择性别',
                    trigger: 'blur'
                }],
                deptId: [
                    {required: true, message: "归属部门不能为空", trigger: "blur"}
                ],
                email: [{
                    pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/,
                    required: false,
                    message: '请输入正确的邮箱格式',
                    trigger: 'blur'
                }],
                tel: [{
                    required: false,
                    message: '请输入用户联系方式',
                    trigger: 'blur'
                }]
            }
        };
    },
    created: function () {
        this.pageUser();
        this.loadAllRoles();
        this.getTreeSelect();
    },
    watch: {
        // 根据名称筛选部门树
        deptName(val) {
            this.$refs.tree.filter(val);
        }
    },
    methods: {
        /** 查询部门下拉树结构 */
        getTreeSelect() {
            let url = "/dept/treeSelect"
            // 查询部门下拉树结构
            this.axios({
                method: "GET",
                url: url,
                data: {},
            }).then(res => {
                this.deptOptions = res.data.data;
            });
        },
        // 筛选节点
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.searchForm.deptId = data.id;
            this.pageUser();
        },
        loadAllRoles: function () { //加载全部可用的角色资源
            let url = LOAD_ROLES_URL;
            this.axios({
                method: "POST",
                url: url
            })
                .then((res) => {
                    this.$data.loading = false;
                    let code = res.data.code;
                    if (code == 200) {
                        this.roles = res.data.data;
                        this.roleOptions = res.data.data.map(item => {
                            return item.id
                        })
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        pageUser: function () {
            this.$data.loading = true;
            let url = LIST_USER_URL + "/" + this.currentPage + "/" + this.pageSize;
            this.axios({
                method: "POST",
                url: url,
                data: this.$data.searchForm,
            })
                .then((res) => {
                    this.$data.loading = false;
                    let code = res.data.code;
                    if (code == 200) {
                        this.$data.tableData = res.data.data.records;
                        this.$data.totalCount = res.data.data.total;
                        this.$data.currentPage = res.data.data.current;
                    } else {
                        this.$message.error("加载资源失败");
                    }
                })
                .catch((error) => {
                    // this.$message.error('加载资源失败');
                    console.log(error);
                });
        },
        // availableFormatter: function (row, column, cellValue) {
        //     return cellValue ? "可用" : "不可用";
        // },
        sexFormatter: function (row, column, cellValue) {
            return cellValue ? "女" : "男";
        },
        carTimeFilter: function (row, column, cellValue) {
            if (cellValue != null) {
                return moment(cellValue).format("YYYY-MM-DD HH:mm:ss");
            }
        },
        onSearch: function () {
            this.currentPage = 1;
            this.pageUser();
        },
        resetSearchForm: function (formName) {
            this.$nextTick(() => {
                this.$refs[formName].resetFields();
                this.onSearch();
            });
        },
        addHandleClick: function () {
            this.$data.isEditor = false;
            this.$data.dialogAddFormVisible = true
            this.$data.form.id = 0;
            this.$nextTick(() => {
                this.$refs['form'].resetFields();
            })
        },
        saveOrUpdate: function () {
            let username = sessionStorage.getItem("username");
            if (this.isEditor && username == this.form.id && this.form.available == 0) {
                this.$message.error("不可禁用当前正在使用的用户！")
                return
            }
            // if (this.$data.isEditor == false) {
            //   this.$data.form.createtime = new Date();
            //   this.$data.form.updatetime = new Date();
            // } else {
            //   this.$data.form.updatetime = new Date();
            // }
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    this.axios({
                        method: 'POST',
                        url: ADD_OR_EDITOR_USER_URL,
                        data: this.form
                    }).then(res => {
                        let code = res.data.code
                        if (code == 200) {
                            this.pageUser();
                            this.$data.dialogAddFormVisible = false
                        } else if(code == 20003){
                            this.$message.error("该用户已存在");
                        } else if(code == 20012){
                          this.$message.error("部门停用，不允许修改");
                        } else {
                            this.$message.error('操作失败');
                        }

                    }).catch(error => {
                        console.log(error);
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        editorHandleClick: function (row) {
            this.isEditor = true;
            this.dialogAddFormVisible = true;
            let url = FIND_USER_URL + "/" + row.id;
            this.axios({
                method: "GET",
                url: url,
                data: {},
            })
                .then((res) => {
                    let code = res.data.code;
                    if (code == 200) {
                        this.$data.form = res.data.data;
                    } else {
                        this.$message.error("加载资源失败");
                    }
                })
                .catch((error) => {
                    // this.$message.error('加载资源失败');
                    console.log(error);
                });
        },
        deleteHandleClick: function (row) {
            let username = sessionStorage.getItem("username");
            console.log(username)
            if (username == row.id) {
                this.$message.error("不可删除当前正在使用的用户！")
                return
            }
            this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$data.ids.push(row.id)
                this.delete()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        delete: function () {
            let data = this.$data.ids
            let urlChild = ''
            data.forEach((e) => {
                urlChild += 'ids=' + e + '&'
            })
            urlChild = urlChild.substring(0, urlChild.lastIndexOf('&'))
            let url = DELETE_USER_URL + '/?' + urlChild

            this.axios({
                method: 'GET',
                url: url,
                data: {}

            }).then(res => {
                let code = res.data.code
                this.$data.ids = new Array()
                if (code == 200) {
                    this.pageUser();
                } else {
                    this.$message.error('操作失败');
                }

            }).catch(error => {
                console.log(error);
            });
        },
        handleSelectionChange: function (val) {
            console.log("handleSelectionChange--", val);
            this.tableChecked = val;
        },
        batchDelete: function (rows) {
            let _this = this;
            console.log(rows.length);
            if (rows.length <= 0) {
                this.$message.warning('请先选择需要删除的数据');
                return;
            }
            _this.$confirm('是否删除选中的所有用户?删除后无法恢复!', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                rows.forEach(element => {
                    _this.ids.push(element.id)
                })
                this.delete()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        handleCurrentChange: function (val) {
            console.log(`当前页: ${val}`);
            this.$data.currentPage = val;
            this.pageUser();
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageSize = val;
            this.pageUser();
        },
        handleCheckAllChange(val) {
            this.checkedRoles = val ? this.roleOptions : [];
            this.isIndeterminate = false;
        },
        handleCheckedRolesChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.roles.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length;
        },
        changeRolesClick: function () { //改变用户角色
            let url = UPDATE_USER_AND_ROLE + "/" + this.authUserId;
            this.axios({
                method: "POST",
                url: url,
                data: this.checkedRoles,
            })
                .then((res) => {
                    let code = res.data.code;
                    if (code == 200) {
                        this.authVisible = false;
                        this.$message.success("设置成功");
                        this.pageUser();
                    } else {
                        this.$message.error("加载资源失败");
                    }
                })
                .catch((error) => {
                    // this.$message.error('加载资源失败');
                    console.log(error);
                });
        },
        roleHandleClick: function (row) {
            this.checkedRoles = [];
            this.authUserId = '';
            this.authVisible = true;
            let that = this
            row.roles.forEach(function (element) {
                that.checkedRoles.push(element.id);
            });
            this.checkAll = this.checkedRoles.length == this.roles.length;
            this.isIndeterminate = this.checkedRoles.length > 0 && this.checkedRoles.length < this.roles.length;
            this.authUserId = row.id
        },
        modifyPasswordHandleClick: function (row) {
            this.password = '';
            this.authUserId = row.id
            this.modifyPasswordVisible = true;
        },
        modifyPasswordClick: function () { //修改密码
            let url = MODIFY_PASSWORD;
            if (this.password.length <= 0) {
                this.$message.warning("密码不能为空");
                return;
            }
            this.axios({
                method: "POST",
                url: url,
                data: {
                    'id': this.authUserId,
                    'password': this.password
                },
            }).then((res) => {
                let code = res.data.code;
                if (code == 200) {
                    this.modifyPasswordVisible = false;
                    this.$message.success("密码修改成功");
                    this.pageUser();
                }
            })
                .catch((error) => {
                    // this.$message.error('加载资源失败');
                    console.log(error);
                });
        },

        resetForm: function (formName) {
            this.$nextTick(() => {
                this.$refs[formName].resetFields();
            });
        },
        handleUpload: function(val) {
            this.form.avatar = val;
        }

    },
};
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.avatar {
    width: 100px;
    height: 100px;
    display: block;
}

</style>